package com.dsunsoft.rtu.core.base;

import com.dsunsoft.rtu.common.entity.BaseEntity;
import com.dsunsoft.rtu.common.entity.BaseQuery;
import com.dsunsoft.rtu.common.entity.RestResult;
import com.dsunsoft.rtu.common.entity.RestCode;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * RestController基类
 *
 * @author ygm
 */
public class BaseRestController<E extends BaseEntity, Q extends BaseQuery> {
    @Autowired
    private BaseService<E, Q> baseService;

    @GetMapping("/{id}")
    public RestResult<E> getById(@PathVariable String id) {
        E entity = baseService.getById(id);
        if (null == entity) {
            return new RestResult<>(RestCode.RETURN_IS_NULL);
        }
        return new RestResult<>(RestCode.SUCCESS, entity);
    }

    @PostMapping("/query")
    public RestResult<List<E>> query(@RequestBody Q query) {
        List<E> list = baseService.queryList(query);
        return new RestResult<>(RestCode.SUCCESS, list);
    }

    @PostMapping("/page")
    public RestResult<PageInfo<E>> queryPage(@RequestBody Q query) {
        PageInfo<E> page = baseService.queryPage(query);
        return new RestResult<>(RestCode.SUCCESS, page);
    }

    @PostMapping
    public RestResult<String> add(@RequestBody @Validated E entity) {
        boolean bl = baseService.insert(entity);
        if (!bl) {
            return new RestResult<String>().failure("保存失败");
        }
        return new RestResult<>(RestCode.SUCCESS);
    }

    @PutMapping
    public RestResult<String> update(@RequestBody @Validated E entity) {
        boolean bl = baseService.update(entity);
        if (!bl) {
            return new RestResult<String>().failure("保存失败");
        }
        return new RestResult<>(RestCode.SUCCESS);
    }

    @DeleteMapping("/{id}")
    public RestResult<String> delete(@PathVariable String id) {
        boolean bl = baseService.deleteById(id);
        if (!bl) {
            return new RestResult<String>().failure("删除失败");
        }
        return new RestResult<>(RestCode.SUCCESS);
    }
}
